home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_10_01 / 1001098d < prev    next >
Text File  |  1991-11-23  |  1KB  |  91 lines

  1.  
  2. Listing 11
  3.  
  4. //
  5. // rational.cpp
  6. //
  7. #include <stdlib.h>
  8. #include "rational.h"
  9.  
  10. rational &rational::operator+=(rational r)
  11.     {
  12.     num = num * r.denom + r.num * denom;
  13.     denom *= r.denom;
  14.     simplify();
  15.     return *this;
  16.     }
  17.  
  18. rational &rational::operator-=(rational r)
  19.     {
  20.     num = num * r.denom - r.num * denom;
  21.     denom *= r.denom;
  22.     simplify();
  23.     return *this;
  24.     }
  25.  
  26. rational &rational::operator*=(rational r)
  27.     {
  28.     num *= r.num;
  29.     denom *= r.denom;
  30.     simplify();
  31.     return *this;
  32.     }
  33.  
  34. rational &rational::operator/=(rational r)
  35.     {
  36.     num *= r.denom;
  37.     denom *= r.num;
  38.     simplify();
  39.     return *this;
  40.     }
  41.  
  42. rational rational::operator+(rational r)
  43.     {
  44.     rational result(*this);
  45.     return result += r;
  46.     }
  47.  
  48. rational rational::operator-(rational r)
  49.     {
  50.     rational result(*this);
  51.     return result -= r;
  52.     }
  53.  
  54. rational rational::operator*(rational r)
  55.     {
  56.     rational result(*this);
  57.     return result *= r;
  58.     }
  59.  
  60. rational rational::operator/(rational r)
  61.     {
  62.     rational result(*this);
  63.     return result /= r;
  64.     }
  65.  
  66. void rational::put(FILE *f)
  67.     {
  68.     fprintf(f, "(%ld/%ld)", num, denom);
  69.     }
  70.  
  71. long gcd(long x, long y)
  72.     {
  73.     x = labs(x);
  74.     y = labs(y);
  75.     while (x != y)
  76.         {
  77.         if (x < y)
  78.             y -= x;
  79.         if (y < x)
  80.             x -= y;
  81.         }
  82.     return x;
  83.     }
  84.  
  85. void rational::simplify()
  86.     {
  87.     long x = gcd(num, denom);
  88.     num /= x;
  89.     denom /= x;
  90.     }
  91.